package net;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;

public class GameServer implements Runnable{
    public ObjectOutputStream oos;
    public ObjectInputStream ois;
	public Socket socket;
	public Thread serverThread;
	public int clientId;
	public UserServer server;

	public GameServer(UserServer _server, Socket serverSocket, int _id){
		server = _server;
		clientId = _id;
		try {
			socket = serverSocket;
			oos = new ObjectOutputStream(socket.getOutputStream());
			ois = new ObjectInputStream(socket.getInputStream());
		} catch (Exception e) {
			e.printStackTrace();
		}
		serverThread = new Thread(this);
		serverThread.start();
	}
	
	public void recieveMessage(Message _msg){
		if(server.gameManager.rules.currentPlayer == clientId || server.gameManager.rules.currentPlayer == -1){
			server.gameManager.handleMessage(clientId, _msg);
		}
	}
	
	public void sendMessage(Message _msg){
		try{
			oos.writeObject(_msg);
		}catch(Exception e){
			e.printStackTrace();
		}
	}
	
	public void run() {
		Message tmp;
		try {
			while(null != (tmp = (Message)ois.readObject())){
				recieveMessage(tmp);
				Thread.yield();
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
